import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"
import AppLayout from '@/layout/AppLayout.vue'
import product from './modules/product'
import order from './modules/order'
import media from './modules/media'
import permission from './modules/permission'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { store } from "@/store"

const routes: RouteRecordRaw[] = [ // 路由规则
  {
    path: '/',
    name: 'AppLayout',
    component: AppLayout,
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('@/views/home/index.vue'),
        meta: { title: '首页', requiresAuth: true },
      },
      product,
      order,
      media,
      permission
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录' }
  }
]

const router = createRouter({
  history: createWebHashHistory(), // 路由模式
  routes
})

router.beforeEach((to, from) => {
  nprogress.start()
  if (to.meta.requiresAuth && !store.state.user) {
    // 此路由需要授权，请检查是否已登录
    // 如果没有，则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置，以便以后再来
      query: { redirect: to.fullPath }
    }
  }
})

router.afterEach(() => {
  nprogress.done()
})

export default router